package com.gxuwz.attend.web.servlet;

import com.gxuwz.attend.context.AppContext;
import com.gxuwz.attend.entity.User;
import com.gxuwz.attend.service.Impl.UserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器（页面控制器）
 * 注意：页面控制器是负责指特定动作处理请求的Servlet对象,一般地，
 * MIS(信息系统)的一个模块(module)包括处理CRUD等类型的动作请求。
 *   前端控制器是负责整个站点所有请求处理的（Servlet和Filter）对象，主流的MVC框架都是基于Servlet或者Filter实现
 *   典型web MVC框架的包括:基于Servlet的springMVC和基于Filter的struts2.
 * 基于Servlet实现的页面控制器都必须继承httpServlet.通常重写doGet|doPost方法。
 * 但是要注意：考虑servlet-api的版本，比如servlet2.5、servlet 6.0等,不同的tomcat支持servlet-api的版本。
 * Note:
 * 1:表示功能模块对应页面的变量，变量命名为view_[add|edit|list]
 * 2:在init()方法中实例化业务逻辑service组件
 */
@WebServlet(name = "userServlet",urlPatterns = {"/user"})
public class UserServlet extends BaseHttpServlet {
    private final Logger logger = LoggerFactory.getLogger(UserServlet.class);
    /*
    * private final static String VIEW_ADD="/WEB-INF/views/user/user_add.jsp";
    private final static String VIEW_EDIT="/WEB-INF/views/user/user_edit.jsp";
    private final static String VIEW_LIST="/WEB-INF/views/user/user_list.jsp";
    * */
    private final static String VIEW_ADD="/WEB-INF/views/user/user_add.jsp";
    private final static String VIEW_EDIT="/WEB-INF/views/user/user_edit.jsp";
    private final static String PERSON_EDIT="/WEB-INF/views/user/person_edit.jsp";
    private final static String VIEW_LIST="/WEB-INF/views/user/user_list.jsp";
    private final static String ACTION_LIST="/user?action=list";
    private final static String VIEW_LOGIN="login.jsp";
    private UserServiceImpl userService;
    @Override
    public void init() throws ServletException {
        super.init();
        userService= AppContext.getBean(UserServiceImpl.class);
    }
    //3:重写doGet|doPost方法

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("..................");
        System.out.println();
//1：接受请求参数action以及其他页面的参数值，按照约定，动作请求action依次为input、add、delete、get、edit、list.
        String action =req.getParameter("action");
        System.out.println("action:" + action);
        String view=ErrorPage_500;
        logger.info("request process starting"+action);
        try {
            //2:调用userService完成处理,此处switch语句的语法要求jdk1.8以上。
            switch (action) {
                case "input":
                    view = VIEW_ADD;
                    User user =new User();
                    user.setUserid("");
                    user.setFullname("");
                    user.setPassword("");
                    user.setTelephone("");
                    req.setAttribute("user",user);
                    break;
                case "add":
                    user =new User();
                    //接收表单(Form)参数,并转换为实体对象的属性值
                    resolveRequestParameter(req,user);
                    //调用service组件完成数据写入
                    //userService.addUser(user);
                    userService.insertUser(user);
                    user.setFullname(null);
                    //指定跳转路径
                    view = ACTION_LIST;
                    break;
                case "delete":
                    String id =req.getParameter("id");
                    userService.deleteUser(id);
                    view = ACTION_LIST;
                    break;
                case "get":
                    id =req.getParameter("id");
                    User user1 = new User();
                    user1.setUserid(id);
                    user = (User) userService.queryUser(user1,id);
                    //清空原有密码
                    //user.setPassword("");
                    view = VIEW_EDIT;
                    req.setAttribute("m",user);
                    break;
                case "edit":
                    user =new User();
                    resolveRequestParameter(req,user);
                    userService.updateUser(user);
                    view = ACTION_LIST;
                    break;
                case "get2":
                    //id =req.getParameter("id");
                    HttpSession session = req.getSession(false);
                    String fullname1 = (String) session.getAttribute("fullname");
                    System.out.println("fullname1:"+fullname1);
                    User user4 = new User();
                    user4.setFullname(fullname1);

                    List<User> userList3 =  userService.queryUsers(user4);
                    user4 = userList3.get(0);
                    //清空原有密码
                    //user4.setPassword("");
                    view = PERSON_EDIT;
                    req.setAttribute("m",user4);
                    break;
                case "person_edit":
                    System.out.println("person_edit");
                    user =new User();
                    resolveRequestParameter(req,user);
                    String userid = req.getParameter("userid");
                    System.out.println("user:"+user +"userid:"+userid);
                    userService.updateUser(user);
                    HttpSession session3 = req.getSession(false);
                    if (session3 != null) {
                        System.out.println("session3:"+session3);
                        // 清除当前用户的会话数据
                        session3.invalidate();
                    }
                    System.out.println("跳转登录页面");
                    // 重定向到登录页面
                    view = VIEW_LOGIN;
                    break;
                case "list":
                    System.out.println(11);
                    String fullname=req.getParameter("fullname11");
                    System.out.println("fullname:"+fullname);
                    if (fullname==null||fullname.isEmpty()){
                        User user2=new User();
                        //查找并显示所有用户信息列表
                        List<User> userList = userService.queryUsers(user2);
                        view = VIEW_LIST;
                        req.setAttribute("list",userList);
                        break;
                    }else{
                        User user3 = new User();
                        user3.setFullname(fullname); // 假设搜索的是用户姓名
                        List<User> userList2 = userService.queryUsers(user3);
                        view = VIEW_LIST;
                        req.setAttribute("list", userList2);
                        break;
                    }
            }
        }catch (Exception e){
            e.printStackTrace();
            req.setAttribute("message",e.getMessage());
            view =ErrorPage_500;
        }
        //3:页面跳转，默认转发方式
        super.doDispatch(req,resp,view);
    }

    /**
     * 解析request参数并转换为POJO对象
     * @param req
     */
    private void resolveRequestParameter(HttpServletRequest req,Object bean){
        Map<String,String[]> reqParameterMap= req.getParameterMap();
        Map<String,String[]> propertiesMap=new HashMap<String,String[]>();
        try {
            for (Map.Entry<String,String[]>  entry : reqParameterMap.entrySet()){
                String name =entry.getKey();
                String[] values=entry.getValue();
                //判断request参数是否对应JavaBean对象的属性
                Class propertyType = PropertyUtils.getPropertyType(bean, name);
                if (propertyType!=null) {
                    propertiesMap.put(name,values);
                }
            }
            //转换为POJO对象bean的属性值
            BeanUtils.populate(bean,propertiesMap);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("The property name could not be found",e);
        }

    }
}
